#!/usr/bin/env python3
# dictionary_server.py
import socket
import threading
import json
from dict_data import DICTIONARY

HOST = "0.0.0.0"   # 监听所有接口
PORT = 50000       # 可按需修改

# 简单 JSON 协议（每次请求/响应一条 JSON，末尾可带换行）
# 请求示例: {"cmd":"lookup","word":"hello"}
# 响应示例: {"status":"ok","word":"hello","translation":"你好"}

lock = threading.Lock()  # 修改字典时要加锁

def handle_client(conn, addr):
    print(f"[+] Connected: {addr}")
    with conn:
        buffer = b""
        while True:
            try:
                data = conn.recv(4096)
            except ConnectionResetError:
                break
            if not data:
                break
            buffer += data
            # 处理按行的 JSON（简单方法）
            while b"\n" in buffer:
                line, buffer = buffer.split(b"\n", 1)
                if not line:
                    continue
                try:
                    req = json.loads(line.decode('utf-8').strip())
                except Exception:
                    resp = {"status":"error","message":"invalid json"}
                    conn.sendall((json.dumps(resp)+"\n").encode('utf-8'))
                    continue

                cmd = req.get("cmd")
                if cmd == "lookup":
                    word = req.get("word","").strip().lower()
                    if not word:
                        resp = {"status":"error","message":"empty word"}
                    else:
                        trans = DICTIONARY.get(word)
                        if trans:
                            resp = {"status":"ok","word":word,"translation":trans}
                        else:
                            resp = {"status":"not_found","word":word}
                elif cmd == "add":
                    word = req.get("word","").strip().lower()
                    trans = req.get("translation","").strip()
                    if not word or not trans:
                        resp = {"status":"error","message":"invalid add params"}
                    else:
                        with lock:
                            DICTIONARY[word] = trans
                        resp = {"status":"ok","message":f"added {word}"}
                elif cmd == "list":
                    with lock:
                        resp = {"status":"ok","count":len(DICTIONARY),"words":list(DICTIONARY.keys())}
                else:
                    resp = {"status":"error","message":"unknown cmd"}
                conn.sendall((json.dumps(resp)+"\n").encode('utf-8'))
    print(f"[-] Disconnected: {addr}")

def main():
    print(f"Starting server on {HOST}:{PORT}")
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((HOST, PORT))
    s.listen(10)
    try:
        while True:
            conn, addr = s.accept()
            t = threading.Thread(target=handle_client, args=(conn, addr), daemon=True)
            t.start()
    except KeyboardInterrupt:
        print("Server stopping...")
    finally:
        s.close()

if __name__ == "__main__":
    main()
